-- dragon_wish_type
-- Created by zhuangsl Oct/8/2015
-- 成就：神龙许愿种类

-- 内部函数声明
local whenDragonWish;

-- 注册神龙许愿的回调
EventMgr.register("game_achievement/dragon_wish_type", event.WISH_DONE, function(args)
    whenDragonWish(args);
end);

-- 注册神龙许愿的回调
whenDragonWish = function(args)
    if not DungeonM.isInDungeon() then
        return false;
    end

    -- 获取许愿信息
    local wishInfo = ME.user.dbase:query("wish_info", {});
    local optionTimes = wishInfo["option_times"] or {};
    local count;
    
    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        -- 统计符合的愿望数量
        count = 0;
        if type(ruleArg) == 'table' and type(ruleArg["wishes"]) == 'table' then
            for _, wishId in pairs(ruleArg["wishes"]) do
                if optionTimes[wishId] ~= nil then
                    count = count + 1;
                end
            end
        end

        if GameAchievementM.getProgress(id) >= count then
            -- 进度没有变化
            return false;
        end 

        return true;
    end
    
    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("dragon_wish_type");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.setProgress(id, count);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);
        
        local progress = config["progress"];
        local desc     = config["desc"];

        desc = string.gsub(desc, "{0}", progress);

        return desc;
    end,
};